//package org.jeecg.modules.deepseek.config;
//
//import io.micrometer.observation.Observation;
//import io.micrometer.observation.ObservationRegistry;
//import java.util.*;
//import java.util.concurrent.ConcurrentHashMap;
//import java.util.stream.Collectors;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.springframework.ai.chat.messages.*;
//import org.springframework.ai.chat.metadata.*;
//import org.springframework.ai.chat.model.*;
//import org.springframework.ai.chat.observation.*;
//import org.springframework.ai.chat.prompt.*;
//import org.springframework.ai.model.Media;
//import org.springframework.ai.model.ModelOptionsUtils;
//import org.springframework.ai.model.tool.*;
//import org.springframework.ai.retry.RetryUtils;
//import org.springframework.http.ResponseEntity;
//import org.springframework.lang.Nullable;
//import org.springframework.retry.support.RetryTemplate;
//import org.springframework.util.*;
//import reactor.core.publisher.Flux;
//import reactor.core.publisher.Mono;
//
//public class DeepSeekChatModel extends AbstractToolCallSupport implements ChatModel {
//    private static final Logger logger = LoggerFactory.getLogger(DeepSeekChatModel.class);
//    private static final ChatModelObservationConvention DEFAULT_OBSERVATION_CONVENTION = new DefaultChatModelObservationConvention();
//    private static final ToolCallingManager DEFAULT_TOOL_CALLING_MANAGER = ToolCallingManager.builder().build();
//
//    // 默认配置选项
//    private final DeepSeekChatOptions defaultOptions;
//    // 重试模板，用于处理请求失败时的重试
//    private final RetryTemplate retryTemplate;
//    // DeepSeek API 客户端
//    private final DeepSeekApi deepSeekApi;
//    // 观察注册器，用于性能监控
//    private final ObservationRegistry observationRegistry;
//    // 工具调用管理器
//    private final ToolCallingManager toolCallingManager;
//    // 观察约定，用于定义监控行为
//    private ChatModelObservationConvention observationConvention;
//
//    // 简单构造函数
//    public DeepSeekChatModel(DeepSeekApi deepSeekApi, DeepSeekChatOptions defaultOptions) {
//        this(deepSeekApi, defaultOptions, DEFAULT_TOOL_CALLING_MANAGER, RetryUtils.DEFAULT_RETRY_TEMPLATE, ObservationRegistry.NOOP);
//    }
//
//    // 完整构造函数
//    public DeepSeekChatModel(DeepSeekApi deepSeekApi, DeepSeekChatOptions defaultOptions,
//                           ToolCallingManager toolCallingManager, RetryTemplate retryTemplate,
//                           ObservationRegistry observationRegistry) {
//        super(null, DeepSeekChatOptions.builder().build(), List.of());
//        this.observationConvention = DEFAULT_OBSERVATION_CONVENTION;
//        Assert.notNull(deepSeekApi, "deepSeekApi cannot be null"); // DeepSeek API 不能为空
//        Assert.notNull(defaultOptions, "defaultOptions cannot be null"); // 默认选项不能为空
//        Assert.notNull(toolCallingManager, "toolCallingManager cannot be null"); // 工具调用管理器不能为空
//        Assert.notNull(retryTemplate, "retryTemplate cannot be null"); // 重试模板不能为空
//        Assert.notNull(observationRegistry, "observationRegistry cannot be null"); // 观察注册器不能为空
//        this.deepSeekApi = deepSeekApi;
//        this.defaultOptions = defaultOptions;
//        this.toolCallingManager = toolCallingManager;
//        this.retryTemplate = retryTemplate;
//        this.observationRegistry = observationRegistry;
//    }
//
//    // 处理同步聊天请求
//    @Override
//    public ChatResponse call(Prompt prompt) {
//        Prompt requestPrompt = buildRequestPrompt(prompt);
//        return internalCall(requestPrompt, null);
//    }
//
//    // 内部调用方法，处理聊天完成
//    public ChatResponse internalCall(Prompt prompt, ChatResponse previousChatResponse) {
//        DeepSeekApi.ChatCompletionRequest request = createRequest(prompt, false);
//        ChatModelObservationContext observationContext = ChatModelObservationContext.builder()
//                .prompt(prompt)
//                .provider("DeepSeek") // 设置提供者为 DeepSeek
//                .requestOptions(prompt.getOptions())
//                .build();
//
//        return ChatModelObservationDocumentation.CHAT_MODEL_OPERATION
//                .observation(observationConvention, DEFAULT_OBSERVATION_CONVENTION,
//                        () -> observationContext, observationRegistry)
//                .observe(() -> {
//                    // 执行 API 调用并处理重试
//                    ResponseEntity<DeepSeekApi.ChatCompletion> completionEntity = retryTemplate.execute(
//                            ctx -> deepSeekApi.chatCompletionEntity(request, getAdditionalHttpHeaders(prompt)));
//
//                    DeepSeekApi.ChatCompletion chatCompletion = completionEntity.getBody();
//                    if (chatCompletion == null) {
//                        logger.warn("没有返回聊天完成结果，提示: {}", prompt);
//                        return new ChatResponse(List.of());
//                    }
//
//                    // 将选择转换为生成结果
//                    List<Generation> generations = chatCompletion.choices().stream()
//                            .map(choice -> {
//                                Map<String, Object> metadata = Map.of(
//                                        "id", Objects.toString(chatCompletion.getId(), ""),
//                                        "role", Objects.toString(choice.message.role(), ""),
//                                        "index", choice.index(),
//                                        "finishReason", Objects.toString(choice.finishReason(), ""));
//                                return buildGeneration(choice, metadata, request);
//                            })
//                            .toList();
//
//                    // 处理使用统计
//                    Usage usage = chatCompletion.getUsage() != null ?
//                            new DefaultUsage(chatCompletion.getUsage().getPromptTokens(),
//                                          chatCompletion.getUsage().getCompletionTokens(),
//                                          chatCompletion.getUsage().getTotalTokens(),
//                                          chatCompletion.getUsage()) :
//                            new EmptyUsage();
//                    Usage accumulatedUsage = UsageUtils.getCumulativeUsage(usage, previousChatResponse);
//
//                    ChatResponse response = new ChatResponse(generations,
//                            from(chatCompletion, null, accumulatedUsage));
//                    observationContext.setResponse(response);
//
//                    // 处理工具调用
//                    if (ToolCallingChatOptions.isInternalToolExecutionEnabled(prompt.getOptions())
//                            && response.hasToolCalls()) {
//                        ToolExecutionResult result = toolCallingManager.executeToolCalls(prompt, response);
//                        return result.returnDirect() ?
//                                ChatResponse.builder().from(response)
//                                        .generations(ToolExecutionResult.buildGenerations(result))
//                                        .build() :
//                                internalCall(new Prompt(result.conversationHistory(), prompt.getOptions()), response);
//                    }
//                    return response;
//                });
//    }
//
//    // 处理流式聊天请求
//    @Override
//    public Flux<ChatResponse> stream(Prompt prompt) {
//        Prompt requestPrompt = buildRequestPrompt(prompt);
//        return internalStream(requestPrompt, null);
//    }
//
//    // 内部流式处理方法
//    public Flux<ChatResponse> internalStream(Prompt prompt, ChatResponse previousChatResponse) {
//        DeepSeekApi.ChatCompletionRequest request = createRequest(prompt, true);
//        Flux<DeepSeekApi.ChatCompletionChunk> completionChunks = deepSeekApi.chatCompletionStream(
//                request, getAdditionalHttpHeaders(prompt));
//
//        ConcurrentHashMap<String, String> roleMap = new ConcurrentHashMap<>();
//        ChatModelObservationContext observationContext = ChatModelObservationContext.builder()
//                .prompt(prompt)
//                .provider("DeepSeek")
//                .requestOptions(prompt.getOptions())
//                .build();
//
//        Observation observation = ChatModelObservationDocumentation.CHAT_MODEL_OPERATION
//                .observation(observationConvention, DEFAULT_OBSERVATION_CONVENTION,
//                        () -> observationContext, observationRegistry);
//
//        Flux<ChatResponse> chatResponse = completionChunks
//                .map(this::chunkToChatCompletion)
//                .switchMap(chatCompletion -> Mono.just(chatCompletion)
//                        .map(completion -> {
//                            List<Generation> generations = completion.getChoices().stream()
//                                    .map(choice -> {
//                                        if (choice.getMessage().getRole() != null) {
//                                            roleMap.putIfAbsent(completion.getId(),  choice.getMessage().getRole());
//                                        }
//                                        Map<String, Object> metadata = Map.of(
//                                                "id", completion.getId(),
//                                                "role", roleMap.getOrDefault(completion.getId(), ""),
//                                                "index", choice.getIndex(),
//                                                "finishReason", Objects.toString(choice.getFinishReason(), ""));
//                                        return buildGeneration(choice, metadata, request);
//                                    })
//                                    .toList();
//
//                            Usage usage = completion.getUsage() != null ?
//                                    new DefaultUsage(completion.getUsage().getPromptTokens(),
//                                            completion.getUsage().getCompletionTokens(),
//                                            completion.getUsage().getTotalTokens(),
//                                            completion.getUsage()) :
//                                    new EmptyUsage();
//                            Usage accumulatedUsage = UsageUtils.getCumulativeUsage(usage, previousChatResponse);
//
//                            return new ChatResponse(generations, from(completion, null, accumulatedUsage));
//                        }))
//                .buffer(2, 1)
//                .map(bufferList -> {
//                    ChatResponse firstResponse = bufferList.get(0);
//                    if (request.streamOptions() != null && bufferList.size() == 2) {
//                        ChatResponse secondResponse = bufferList.get(1);
//                        if (secondResponse != null && secondResponse.getMetadata() != null) {
//                            Usage usage = secondResponse.getMetadata().getUsage();
//                            if (!UsageUtils.isEmpty(usage)) {
//                                return new ChatResponse(firstResponse.getResults(),
//                                        from(firstResponse.getMetadata(), usage));
//                            }
//                        }
//                    }
//                    return firstResponse;
//                });
//
//        Flux<ChatResponse> flux = chatResponse.flatMap(response -> {
//            if (ToolCallingChatOptions.isInternalToolExecutionEnabled(prompt.getOptions())
//                    && response.hasToolCalls()) {
//                ToolExecutionResult result = toolCallingManager.executeToolCalls(prompt, response);
//                return result.returnDirect() ?
//                        Flux.just(ChatResponse.builder().from(response)
//                                .generations(ToolExecutionResult.buildGenerations(result))
//                                .build()) :
//                        internalStream(new Prompt(result.conversationHistory(), prompt.getOptions()), response);
//            }
//            return Flux.just(response);
//        }).doOnError(observation::error)
//          .doFinally(s -> observation.stop());
//
//        MessageAggregator aggregator = new MessageAggregator();
//        return aggregator.aggregate(flux, observationContext::setResponse);
//    }
//
//    // 获取额外的 HTTP 头
//    private MultiValueMap<String, String> getAdditionalHttpHeaders(Prompt prompt) {
//        Map<String, String> headers = new HashMap<>(defaultOptions.getHttpHeaders());
//        if (prompt.getOptions() instanceof DeepSeekChatOptions) {
//            headers.putAll(((DeepSeekChatOptions) prompt.getOptions()).getHttpHeaders());
//        }
//        return CollectionUtils.toMultiValueMap(
//                headers.entrySet().stream()
//                        .collect(Collectors.toMap(Map.Entry::getKey, e -> List.of(e.getValue()))));
//    }
//
//    // 构建生成结果
//    private Generation buildGeneration(DeepSeekApi.ChatCompletion.Choice choice,
//                                     Map<String, Object> metadata,
//                                     DeepSeekApi.ChatCompletionRequest request) {
//        List<AssistantMessage.ToolCall> toolCalls = choice.getMessage().toolCalls() == null ?
//                List.of() :
//                choice.getMessage().toolCalls().stream()
//                        .map(tc -> new AssistantMessage.ToolCall(tc.getId(), "function",
//                                tc.function().name(), tc.function().arguments()))
//                        .toList();
//
//        ChatGenerationMetadata generationMetadata = ChatGenerationMetadata.builder()
//                .finishReason(Objects.toString(choice.finishReason(), ""))
//                .build();
//
//        AssistantMessage assistantMessage = new AssistantMessage(
//                choice.getMessage().content(), metadata, toolCalls, List.of());
//        return new Generation(assistantMessage, generationMetadata);
//    }
//
//    // 从完成结果构建元数据
//    private ChatResponseMetadata from(DeepSeekApi.ChatCompletion result,
//                                    RateLimit rateLimit,
//                                    Usage usage) {
//        ChatResponseMetadata.Builder builder = ChatResponseMetadata.builder()
//                .id(Objects.toString(result.getId(), ""))
//                .usage(usage)
//                .model(Objects.toString(result.model(), ""))
//                .keyValue("created", result.created() != null ? result.created() : 0L);
//
//        if (rateLimit != null) {
//            builder.rateLimit(rateLimit);
//        }
//        return builder.build();
//    }
//
//    // 从现有元数据构建新元数据
//    private ChatResponseMetadata from(ChatResponseMetadata metadata, Usage usage) {
//        ChatResponseMetadata.Builder builder = ChatResponseMetadata.builder()
//                .id(Objects.toString(metadata.getId(), ""))
//                .usage(usage)
//                .model(Objects.toString(metadata.getModel(), ""));
//
//        if (metadata.getRateLimit() != null) {
//            builder.rateLimit(metadata.getRateLimit());
//        }
//        return builder.build();
//    }
//
//    // 将块转换为完成结果
//    private DeepSeekApi.ChatCompletion chunkToChatCompletion(DeepSeekApi.ChatCompletionChunk chunk) {
//        List<DeepSeekApi.ChatCompletion.Choice> choices = chunk.getChoices().stream()
//                .map(c -> new DeepSeekApi.ChatCompletion.Choice(
//                        c.getFinishReason(), c.getIndex(), c.getDelta(), c.getLogprobs()))
//                .toList();
//        return new DeepSeekApi.ChatCompletion(chunk.getId(), choices, chunk.getCreated(),
//                chunk.getModel(), null, null, "chat.completion", chunk.getUsage());
//    }
//
//    // 构建请求提示
//    private Prompt buildRequestPrompt(Prompt prompt) {
//        DeepSeekChatOptions runtimeOptions = prompt.getOptions() != null ?
//                ModelOptionsUtils.copyToTarget(prompt.getOptions(),
//                        ChatOptions.class, DeepSeekChatOptions.class) : null;
//
//        DeepSeekChatOptions requestOptions = (DeepSeekChatOptions) ModelOptionsUtils.merge(
//                runtimeOptions, defaultOptions, DeepSeekChatOptions.class);
//
//        return new Prompt(prompt.getInstructions(), requestOptions);
//    }
//
//    // 创建 API 请求
//    private DeepSeekApi.ChatCompletionRequest createRequest(Prompt prompt, boolean stream) {
//        List<DeepSeekApi.ChatCompletionMessage> messages = prompt.getInstructions().stream()
//                .map(message -> new DeepSeekApi.ChatCompletionMessage(
//                        message.getText(),
//                        DeepSeekApi.ChatCompletionMessage.Role.valueOf(
//                                message.getMessageType().name())))
//                .toList();
//
//        DeepSeekChatOptions options = (DeepSeekChatOptions) prompt.getOptions();
//        DeepSeekApi.ChatCompletionRequest request = new DeepSeekApi.ChatCompletionRequest(messages, stream);
//        return (DeepSeekApi.ChatCompletionRequest) ModelOptionsUtils.merge(options, request,
//                DeepSeekApi.ChatCompletionRequest.class);
//    }
//
//    // 获取默认选项
//    @Override
//    public ChatOptions getDefaultOptions() {
//        return DeepSeekChatOptions.fromOptions(defaultOptions);
//    }
//
//    // 构建器类
//    public static class Builder {
//        private DeepSeekApi deepSeekApi;
//        private DeepSeekChatOptions defaultOptions = DeepSeekChatOptions.builder()
//                .model("deepseek-default")
//                .temperature(0.7)
//                .build();
//        private ToolCallingManager toolCallingManager = DEFAULT_TOOL_CALLING_MANAGER;
//        private RetryTemplate retryTemplate = RetryUtils.DEFAULT_RETRY_TEMPLATE;
//        private ObservationRegistry observationRegistry = ObservationRegistry.NOOP;
//
//        public Builder deepSeekApi(DeepSeekApi deepSeekApi) {
//            this.deepSeekApi = deepSeekApi;
//            return this;
//        }
//
//        public Builder defaultOptions(DeepSeekChatOptions defaultOptions) {
//            this.defaultOptions = defaultOptions;
//            return this;
//        }
//
//        public Builder toolCallingManager(ToolCallingManager toolCallingManager) {
//            this.toolCallingManager = toolCallingManager;
//            return this;
//        }
//
//        public DeepSeekChatModel build() {
//            return new DeepSeekChatModel(deepSeekApi, defaultOptions,
//                    toolCallingManager, retryTemplate, observationRegistry);
//        }
//    }
//}